package com.chensi.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.chensi.common.AjaxJson;
import com.chensi.common.Constants;

/**
 * 公共api--文件上传接口
 * @author chensi
 * @version 2016-6-1 下午4:51:30
 */
@Controller
@RequestMapping("/api")
public class UploadApi {
	
	private static final Logger log=LoggerFactory.getLogger(UploadApi.class);
	/**
	 * 支持多文件上传
	 * @param request
	 * @return
	 */
	@RequestMapping("upload")
	@ResponseBody
	public AjaxJson upload(HttpServletRequest request){
		try {
			if (!(request instanceof MultipartHttpServletRequest)){
				return AjaxJson.getFailInfo("没有文件");
			}
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			String relativePath=Constants.UPLOAD_FILE+new SimpleDateFormat("yyyy/MM/dd").format(new Date());
			String ctxPath = request.getSession().getServletContext().getRealPath("/") + relativePath;
			File file = new File(ctxPath);// 
			if (!file.exists()) {
				file.mkdirs();
			}
			String fileName = null;
			StringBuffer sb=new StringBuffer();
			for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
				// 上传文件名 //
				MultipartFile mf = entity.getValue();
				fileName = mf.getOriginalFilename();
				if ("".equals(fileName)) {
					continue;
				}
				String format=mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf("."));
				fileName=""+System.currentTimeMillis()+new Random().nextInt(100000);
				File uploadFile = new File(ctxPath +"/"+ fileName+format);
				FileCopyUtils.copy(mf.getBytes(), uploadFile);
				sb.append(relativePath+"/"+ fileName+format+",");
			}
			String result=sb.deleteCharAt(sb.lastIndexOf(",")).toString();
			log.warn("文件上传成功： "+result);
			return AjaxJson.getSuccessInfo(result);
		} catch (IOException e) {
			e.printStackTrace();
			log.error("上传文件失败");
			return AjaxJson.getFailInfo();
		}
	}
}
